#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        int n = 0;
        ListNode* cur = head;
        while (cur)
        {
            cur = cur->next;
            ++n;
        }
        if (n <= 1 || k == 0 || (k % n) == 0) return head;
        k %= n;
        k = n - k;
        cur = head;
        while (--k)
        {
            cur = cur->next;
        }
        ListNode* phead = cur->next;
        cur->next = nullptr;
        cur = phead;
        while (cur->next)
        {
            cur = cur->next;
        }
        cur->next = head;
        return phead;
    }
};